<?php defined('BASEPATH') or exit('No direct script access allowed');

class Shows_m extends MY_Model {
	
	function __construct(){
		parent::__construct();
		$this->load->library('module_helper');
		$this->load->library('country_city');
	}
	
	function index(){
		$USER = $this->user_entity->init('id',$_SESSION['user']['id']);
		
		if($USER->getBuyerType() == 'general'){
			$cond1 = " AND bid_type LIKE 'public'";
		}else if($USER->getBuyerType() == 'corporate_brand'){
			$cond1 = " AND bid_type IN ('public','commercial')";
		}else if($USER->getBuyerType() == 'vip'){
			$cond1 = " AND bid_type IN ('public','private')";
		}
		
		$country_origin_arr = explode(',',$USER->getCountryOrigin());
		if(!empty($country_origin_arr)){
			$c1 = array();
			foreach($country_origin_arr as $item){
				$c1[] = " country_origin_code LIKE '$item' ";
			}
			$cc1 = implode(' OR ',$c1);
		}else{
			$cc1 = ' 1 ';
		}
		
		$music_genre_arr = explode(',',$USER->getMusicGenre());
		if(!empty($music_genre_arr)){
			$c2 = array();
			foreach($music_genre_arr as $item){
				$c2[] = " music_genre LIKE '%$item%' ";
			}
			$cc2 = implode(' OR ',$c2);
		}else{
			$cc2 = ' 1 ';
		}
		
		$cond2 = " AND ( $cc1 OR $cc2)";
		
		$where = "status IN('closed', 'cancelled', 'opening') ".$cond1.$cond2;//.$cond2
		 
		$total = count( $this->db->where($where)->get(TBL_SHOW)->result() );
		$records_per_page = isset($_GET['records_per_page']) ? intval($_GET['records_per_page']) : defaultNumberRecordsPerPageShowDataConfig();
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 0;
		
		$partial = array();
		foreach($_GET as $key=> $value){
			if($key != "per_page")
				$partial["$key"] = "$key=$value";
		}
		
		$pagination = create_pagination( 
								$uri = 'buyer/shows/?'.implode('&',$partial), 
								$total_rows = $total , 
								$limit= $records_per_page,
								$uri_segment = 0,
								TRUE, TRUE 
							);
	 	 
		$records = $this->db->where($where)->order_by('id','desc')->limit($records_per_page, $per_page )->get(TBL_SHOW)->result();
		return array('pagination'=> $pagination, 'items'=>$records, 'total_records'=>$total);
	}
	
	function search(){
		$USER = $this->user_entity->init('id',$_SESSION['user']['id']);
		
		if($USER->getBuyerType() == 'general'){
			$cond1 = " AND bid_type LIKE 'public'";
		}else if($USER->getBuyerType() == 'corporate_brand'){
			$cond1 = " AND bid_type IN ('public','commercial')";
		}else if($USER->getBuyerType() == 'vip'){
			$cond1 = " AND bid_type IN ('public','private')";
		}
		
		$country_origin_arr = explode(',',$USER->getCountryOrigin());
		if(!empty($country_origin_arr)){
			$c1 = array();
			foreach($country_origin_arr as $item){
				$c1[] = " country_origin_code LIKE '$item' ";
			}
			$cc1 = implode(' OR ',$c1);
		}else{
			$cc1 = ' 1 ';
		}
		
		$music_genre_arr = explode(',',$USER->getMusicGenre());
		if(!empty($music_genre_arr)){
			$c2 = array();
			foreach($music_genre_arr as $item){
				$c2[] = " music_genre LIKE '%$item%' ";
			}
			$cc2 = implode(' OR ',$c2);
		}else{
			$cc2 = ' 1 ';
		}
		
		$cond2 = " AND ( $cc1 OR $cc2)";
		
		$condition = array();
		if($_GET['title'] != "Title"){
			$title = mysql_real_escape_string(strtolower($_GET['title']));
			$condition[] = " LOWER(name) LIKE '$title%' ";
		}
		if($_GET['country_origin'] != ""){
			$country_origin = mysql_real_escape_string(strtolower($_GET['country_origin']));
			$condition[] = " country_origin_code LIKE '$country_origin' ";
		}
		if($_GET['artist'] != "Artist"){
			$artist = mysql_real_escape_string(strtolower($_GET['artist']));
			$condition[] = " artist LIKE '$artist%' ";
		}
		if($_GET['bid'] != "Minimum bid"){
			$bid = intval($_GET['bid']);
			$condition[] = " min_bid >= $bid ";
		}
		if($_GET['show_type'] != "" ){
			$show_type = mysql_real_escape_string($_GET['show_type']);
			$condition[] = " show_type LIKE '$show_type' ";
		}
		if($_GET['start_date'] != "From Date"){
			$start_date = convertToTimeStampFromFormat('j-M-Y',$_GET['start_date']);
			if($start_date != 0){
				$condition[] = " start_date >= $start_date ";
			}
		}
		if($_GET['end_date'] != "To Date"){
			$end_date = convertToTimeStampFromFormat('j-M-Y',$_GET['end_date']);
			if($end_date != 0){
				$condition[] = " end_date <= $end_date ";
			}
		}
		if($_GET['show_status'] != ""){
			$show_status = mysql_real_escape_string($_GET['show_status']);
			$condition[] = " status LIKE '$show_status' ";
		}
		$condition_str = implode('AND', $condition);
	    $condition_str = !empty($condition_str) ? $condition_str : '1';
		$condition_str .= $cond1.$cond2;
	 	
		$total = count( $this->db->query("SELECT * FROM ".TBL_SHOW." WHERE $condition_str AND status != 'confirm' AND status != 'pending' ")->result() ); 
		$records_per_page = isset($_GET['records_per_page']) ? intval($_GET['records_per_page']) : defaultNumberRecordsPerPageShowDataConfig();
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 0;
		
		$partial = array();
		foreach($_GET as $key=> $value){  
			if($key != "per_page")
				$partial["$key"] = "$key=".urlencode($value);
		}
	 
		$pagination = create_pagination( 
								$uri = 'buyer/shows/search/?'.implode('&',$partial), 
								$total_rows = $total , 
								$limit= $records_per_page,
								$uri_segment = 0,
								TRUE, TRUE 
							);
	 	 
		$records = $this->db->query("SELECT * FROM ".TBL_SHOW." WHERE $condition_str AND status != 'confirm' AND status != 'pending' ORDER BY id DESC LIMIT $per_page, $records_per_page")->result();
		return array('pagination'=> $pagination, 'items'=>$records, 'total_records'=>$total);
	}
	
	function view(){
		$ref_no = $this->uri->segment(4,0);
		$SHOW = $this->show_entity->init('ref_no',$ref_no);
		if(! $SHOW){
			show_404(); exit();
		}
		return $SHOW;
	}
	
	function bid(){
		$SHOW = $this->show_entity->init('ref_no', $this->input->get('ref_no','') );
		
		if( !$SHOW || $SHOW->makescrid() != $this->input->get('scrid','') ){
			show_404();exit();
		}
		
		$default_country = $this->country_city->getCountryRecordsBy_zonecode("asia");
		$default_city = $this->country_city->getCityRecordsBy_countryid($default_country[0]->id);
		return array('show'=>$SHOW, 'country'=>$default_country, 'city'=>$default_city );
	}
	
	function ajax_changeZone(){
		$zone_id = ($_POST['value']);
		$position_id = $_POST['positionId'];
		
		$records = $this->country_city->getCountryRecordsBy_zonecode($zone_id);
		$options = array();
		if(!empty($records)){
			foreach($records as $record){
				$options[$record->id] = $record->name;
			}
		}else{
			$options[0] = "";
		}
		echo form_dropdown( 'country[]',
							$options,
							$selected = array(),
							"id='country[]' class='width270' onchange='changeCountry(\"$position_id\",this.value);'"
						);	
		exit();	
	}
	
	function ajax_changeCountry(){
		$country_id = intval($_POST['value']);
		$position_id = $_POST['positionId'];
		
		$city_records = $this->country_city->getCityRecordsBy_countryid($country_id);
		$options = array();
		if(!empty($city_records)){
			foreach($city_records as $record){
				$options[$record->id] = $record->name;
			}
		}else{
			$options[0] = "";
		}
		echo form_dropdown( 'city[]',
							$options,
							$selected = array(),
							"id='city[]' class='width270'"
						);	
		exit();				
	}
	
	function ajax_addBookingfor(){
		$currentItem = intval($_POST['currentItem']);
		
		$default_country = $this->country_city->getCountryRecordsBy_zonecode("asia");
		$default_city = $this->country_city->getCityRecordsBy_countryid($default_country[0]->id);
		
		return array( 'country'=>$default_country, 'city'=>$default_city , 'curItem'=>$currentItem+1 );
	}
	
	function submit_bid(){
		$ref_no = $this->input->post('ref_no','');
		$scrid = $this->input->post('scrid','');
		
		$SHOW = $this->show_entity->init('ref_no', $ref_no );
		
		if( !$SHOW || $SHOW->makescrid() != $scrid ){
			exit();
		}
		$MY_ACC = $this->user_entity->init('id', $_SESSION['user']['id']);
		
		$howManyBookingItems = count($_POST['booking_for']);
		for($i = 0; $i< $howManyBookingItems; $i++){
			$newBookingId = $this->booking_entity->createNewBookingEntity($MY_ACC->getAccCode(), $SHOW->getRefNo() );
			$BOOKING = $this->booking_entity->init('id',$newBookingId);
			
			$BOOKING->setBookingFor($_POST['booking_for'][$i]);
			$BOOKING->setCountry($_POST['country'][$i]);
			$BOOKING->setCity($_POST['city'][$i]);
			$BOOKING->setVenue($_POST['venue'][$i]);
			$BOOKING->setAddress($_POST['address'][$i]);
			$BOOKING->setCapacity($_POST['capacity'][$i]);
			$BOOKING->setTicketPrice($_POST['ticket_pricing'][$i]);
			$BOOKING->setPotentialSponsors($_POST['potential_sponsors'][$i]);
			
			$BOOKING->update();
		}
		
		$newBidId = $this->bid_entity->createNewBidEntity( $MY_ACC->getAccCode(), $SHOW->getRefNo() );
		$BID = $this->bid_entity->init('id', $newBidId);
		
		$BID->setOfferPrice($this->input->post('offer_price',0));
		$BID->setArtistProduction1($this->input->post('artist_production1',''));
		$BID->setArtistProduction2($this->input->post('artist_production2',''));
		$BID->setArtistProduction3($this->input->post('artist_production3',''));
		$BID->setArtistProduction4($this->input->post('artist_production4',''));		
		$BID->setYear1($this->input->post('year1',0));
		$BID->setYear2($this->input->post('year2',0));
		$BID->setYear3($this->input->post('year3',0));
		$BID->setYear4($this->input->post('year4',0));
		$BID->setCapacity1($this->input->post('capacity1',''));	
		$BID->setCapacity2($this->input->post('capacity2',''));	
		$BID->setCapacity3($this->input->post('capacity3',''));	
		$BID->setCapacity4($this->input->post('capacity4',''));	
		$BID->setVenue1($this->input->post('venue1',''));
		$BID->setVenue2($this->input->post('venue2',''));
		$BID->setVenue3($this->input->post('venue3',''));
		$BID->setVenue4($this->input->post('venue4',''));
		$BID->setDateBid(time());
		
		$BID->update();
		
		//send email
		$this->crontab_email->cronUpdate("NEWBIDSUBMIT_".$SHOW->getRefNo(),'_sendEmailToUser_newBidSubmit', strval($SHOW->getRefNo().",".$newBidId), array(time()) );
			
		echo 'ok#'.site_url("buyer/shows/bid_notify");exit();
	}
	
	function edit_bid(){
		$SHOW = $this->show_entity->init('ref_no', $this->input->get('ref_no','') );
		$MY_ACC = $this->user_entity->init('id', $_SESSION['user']['id']);
		if( !$SHOW || $SHOW->makescrid() != $this->input->get('scrid','') ){
			show_404();exit();
		}		
		$BID = $this->bid_entity->is_set($MY_ACC->getAccCode(), $SHOW->getRefNo());
		if(! $BID){
			show_404();exit();
		}
		
		return array( 'bid'=>$BID, 'booking'=> $this->booking_entity->is_set_array($MY_ACC->getAccCode(), $SHOW->getRefNo()));
	}
	
/*	function removeBooking(){
		$booking_id = intval($_POST['booking_id']);
		$MY_ACC = $this->user_entity->init('id', $_SESSION['user']['id']);
		$BOOKING = $this->booking_entity->init('id', $booking_id); 
		
		if($BOOKING->getAccountCode() != $MY_ACC->getAccCode() ){
			exit();
		}
		$this->db->where('id',$booking_id)->delete(TBL_BOOKING_FOR);
		echo 'ok';exit();
	}
*/	
	function submit_edit_bid(){
		$ref_no = $this->input->post('ref_no','');
		$scrid = $this->input->post('scrid','');
		
		$SHOW = $this->show_entity->init('ref_no', $ref_no );
		
		if( !$SHOW || $SHOW->makescrid() != $scrid ){
			exit();
		}
		$MY_ACC = $this->user_entity->init('id', $_SESSION['user']['id']);
		
		$howManyBookingItems = count($_POST['booking_for']);
		$howManyBookingItemsExisted = count($_POST['edit_id']);
		
		$booking_records = $this->db->where( array('account_code'=>$MY_ACC->getAccCode(), 'show_ref_no'=>$SHOW->getRefNo()) )->get(TBL_BOOKING_FOR)->result();
		$book_old_arr = array();
		foreach($booking_records as $book_obj){
			$book_old_arr[] = $book_obj->id;
		}
		$book_new_arr = array_values($_POST['edit_id']);
		
		$book_will_remove = array_diff($book_old_arr, $book_new_arr);
		foreach($book_will_remove as $item_id){
			$this->db->where('id', $item_id)->delete(TBL_BOOKING_FOR);
		}
		
		
		for($i = 0; $i< $howManyBookingItems; $i++){
			if($i< $howManyBookingItemsExisted ){ // edit item
				$BOOKING = $this->booking_entity->init('id',$_POST['edit_id'][$i]);
			}else{ // add new item
				$newBookingId = $this->booking_entity->createNewBookingEntity($MY_ACC->getAccCode(), $SHOW->getRefNo() );
				$BOOKING = $this->booking_entity->init('id',$newBookingId);
			}
		
			$BOOKING->setBookingFor($_POST['booking_for'][$i]);
			$BOOKING->setCountry($_POST['country'][$i]);
			$BOOKING->setCity($_POST['city'][$i]);
			$BOOKING->setVenue($_POST['venue'][$i]);
			$BOOKING->setAddress($_POST['address'][$i]);
			$BOOKING->setCapacity($_POST['capacity'][$i]);
			$BOOKING->setTicketPrice($_POST['ticket_pricing'][$i]);
			$BOOKING->setPotentialSponsors($_POST['potential_sponsors'][$i]);
			
			$BOOKING->update();
		}
	
		$BID = $this->bid_entity->init( 'id', intval($_POST['bid_id']) );
		
		$BID->setOfferPrice($this->input->post('offer_price',0));
		$BID->setArtistProduction1($this->input->post('artist_production1',''));
		$BID->setArtistProduction2($this->input->post('artist_production2',''));
		$BID->setArtistProduction3($this->input->post('artist_production3',''));
		$BID->setArtistProduction4($this->input->post('artist_production4',''));		
		$BID->setYear1($this->input->post('year1',0));
		$BID->setYear2($this->input->post('year2',0));
		$BID->setYear3($this->input->post('year3',0));
		$BID->setYear4($this->input->post('year4',0));
		$BID->setCapacity1($this->input->post('capacity1',''));	
		$BID->setCapacity2($this->input->post('capacity2',''));	
		$BID->setCapacity3($this->input->post('capacity3',''));	
		$BID->setCapacity4($this->input->post('capacity4',''));	
		$BID->setVenue1($this->input->post('venue1',''));
		$BID->setVenue2($this->input->post('venue2',''));
		$BID->setVenue3($this->input->post('venue3',''));
		$BID->setVenue4($this->input->post('venue4',''));
		$BID->setDateBid(time());
		
		$BID->update();
		
		//send email
		$this->crontab_email->cronUpdate("BIDEDIT_".$SHOW->getRefNo(),'_sendEmailToUser_bidEdit', strval($SHOW->getRefNo().",".$BID->getId()), array(time()) );
			
		echo 'ok#'.site_url("buyer/shows/edit_bid_notify");exit();		
	}
	
	function submitQuestionSeller(){
		$SHOW = $this->show_entity->init('ref_no', $_POST['ref_no']);
		$subject = $_POST['subject'];
		$message = $_POST['message'];
		$MY_ACC = $this->user_entity->init('id', $_SESSION['user']['id']);
		
		$this->db->set('buyer_acc_code', $MY_ACC->getAccCode());
		$this->db->set('show_ref_no', $SHOW->getRefNo());
		$this->db->set('subject',  $_POST['subject']);
		$this->db->set('message', $_POST['message']);
		$this->db->insert(TBL_BUYER_MESSAGE);
		
		$inserted_id = $this->db->insert_id();
		
		$this->crontab_email->cronUpdate("SENDQUESTIONTOSELLER_".$SHOW->getRefNo(),'_sendEmail_Buyer2Seller', $inserted_id, array(time()) );
		
		echo 'ok';exit();
	}
	
	
	
}